package org.diysearch.services;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.helpers.LinkHelper;
import org.diysearch.interfaces.Product;
import org.diysearch.models.Link;
import org.diysearch.models.Status;
import org.diysearch.products.JsonProduct;

public class SaveLink extends BaseService {
	private static final Log LOG = LogFactory.getLog(SaveLink.class);
	private String uri;
	
	@Override
	public Product execute() throws Exception {
		Product p = new JsonProduct();
		Status s = new Status();
		
		p.setWriter(writer);
		
		String title 		= request.getParameter("title");
		String url 			= request.getParameter("url");
		int category 		= Integer.parseInt(request.getParameter("categoryId"));
		String description 	= request.getParameter("description");
		int id 				= Integer.parseInt(request.getParameter("id"));
		
		Link link = new Link();
		link.setId(id);
		link.setTitle(title);
		link.setCategory(category);
		link.setDescription(description);
		link.setUrl(url);
		link.setIsActive(0);
		
		try {
			int code = LinkHelper.save(link);
			s.setCode(code);
			s.setMessage("link '"+link.getTitle()+"' saved");
		} catch (Exception ex) {
			s.setCode(-1);
			s.setMessage("something happened where your changes were not saved");
			LOG.warn("Link changes failed: "+ link.getId(),ex);
		}
		p.setOutput(s);
		return p;
	}

	@Override
	public boolean isWriter() {
		return true;
	}

	@Override
	public String getUri() {
		return uri;
	}

	@Override
	public void setUri(String uri) {
		this.uri = uri;
	}

}
